package dxn.nl.export.deal.consumer;

import dxn.boot.common.config.CsApplicationContext;
import dxn.nl.export.deal.netty.SocketManager;
import dxn.nl.export.deal.service.ExportFileService;
import dxn.nl.export.deal.service.ImportFileService;
import dxn.nl.file.biz.service.ConsumerBaseService;
import dxn.nl.file.client.model.enums.ExportFileTypeEnum;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class ExportDealConsumer implements Runnable{
    private static final Logger logger = LoggerFactory.getLogger(ExportDealConsumer.class);
    private long id;
    private int typeCode;
    private ConsumerBaseService consumerBaseService;
    private ExportFileService exportFileService;

    private ImportFileService importFileService;

    public ExportDealConsumer(long id,int typeCode) {
        this.id = id;
        this.typeCode = typeCode;
        consumerBaseService = CsApplicationContext.getBean(ConsumerBaseService.class);
        exportFileService = CsApplicationContext.getBean(ExportFileService.class);
        importFileService = CsApplicationContext.getBean(ImportFileService.class);
    }

    @Override
    public void run() {
        try {
            String threadId = SocketManager.appSessionId + Thread.currentThread().getId();
            // 锁定id
            boolean locked = consumerBaseService.lockId(id, typeCode, threadId);
            if (!locked) {
                return;
            }
            try {
                if(typeCode == ExportFileTypeEnum.export.code)
                {
                    ThreadManager.exportCache.put(id, threadId);
                    // 执行导出
                    exportFileService.dealExportFile(id);
                }
               else {
                    ThreadManager.uploadCache.put(id, threadId);
                    // 执行导出
                    importFileService.dealImportFile(id);
                }
                // 释放id
                locked =consumerBaseService.unlockId(id, typeCode, 2, threadId);
                if(!locked)
                {
                    logger.warn(id+"释放锁失败");
                }
            } catch (Exception ex) {
                logger.error("",ex);
                consumerBaseService.unlockId(id, typeCode, 0, threadId);
            }
        } catch (Exception ex)
        {
            logger.error("",ex);
        }
        finally {
            if(typeCode == ExportFileTypeEnum.export.code)
            {
                ThreadManager.exportCache.remove(id);
            }
            else {
                ThreadManager.uploadCache.remove(id);
            }
        }
    }
}
